package org.zjt.auth.security;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {

  @Value("${youran.token.header}")
  private String tokenHeader;

  @Autowired
  private TokenUtils tokenUtils;

  @Autowired
  private UserDetailsService userDetailsService;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    String userDetailsJson=this.tokenUtils.getUsernameFromToken(authToken);
    SecurityUser userDetails = StringUtils.isEmpty(userDetailsJson) ? null : JSONObject.parseObject(userDetailsJson,SecurityUser.class);

    if ( userDetails ==null)
      SecurityContextHolder.getContext().setAuthentication(null);

    // 用页面传过来的token，以及token中携带的用户名，查询该token是否ok，从而知道是否认证成功。
    if (userDetails != null && !StringUtils.isEmpty(userDetails.getUsername())   && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails tmp = this.userDetailsService.loadUserByUsername(userDetails.getUsername());
      if (this.tokenUtils.validateToken(authToken, tmp)) {//token有效的
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(tmp, null, tmp.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
        SecurityContextHolder.getContext().setAuthentication(authentication);
      }
    }

    chain.doFilter(request, response);
  }

  public static void main(String [] ARGS){
    String str ="{\"accountNonExpired\":true,\"accountNonLocked\":true,\"authorities\":[{\"authority\":\"USER\"}],\"credentialsNonExpired\":true,\"enabled\":true,\"password\":\"ZHANG\",\"username\":\"zhang\"}";


    UserDetails userDetails =JSONObject.parseObject(str,UserDetails.class);






  }

}
